#include "rtc.h"
#include <stdio.h>




static uint16_t time_arry [7];

/**
 * @desc  : RTC设置
 * @date  : 2025-02-19
 * @author: AnRui
 * @note  :
 */
void RTC_config() {
    // 电池管理加载 
    rcu_periph_clock_enable(RCU_PMU);
    pmu_backup_write_enable();
    // 晶振加载
    rcu_osci_on(RCU_LXTAL);
    rcu_osci_stab_wait(RCU_LXTAL);
    rcu_rtc_clock_config(RCU_RTCSRC_LXTAL);
    // RTC功能加载
    rcu_periph_clock_enable(RCU_RTC);
    rtc_register_sync_wait();
    // 设置初始时间
    rtc_parameter_struct rps;
    rps.year = WRITE_BCD(dft_year);
    rps.month = WRITE_BCD(dft_month);
    rps.date = WRITE_BCD(dft_date);
    rps.day_of_week = dft_week;
    rps.hour = WRITE_BCD(dft_hour);
    rps.minute = WRITE_BCD(dft_minute);
    rps.second = WRITE_BCD(dft_second);
    rps.display_format = date_formate;
    rps.am_pm = (dft_hour >= 0 && dft_hour < 12) ? RTC_AM : RTC_PM;
    // RTC内部有一个7位异步分频器 一个15位同步分频器 把32.867kHZ 降为1HZ使用
    //     1 = 32.768k / (asyn + 1) / (syn + 1)
    //     ● asyn取值范围为0到0x7F
    //     ● syn取值范围为0到0x7FFF
    //     手册上要求 : 异步分频器 要尽可能大 所以 asyn取值为0x7F, 由此可得 syn : 0xFF
    rps.factor_asyn = 0x7F;
    rps.factor_syn = 0xFF;
    rtc_init(&rps);
}

/**
 * @desc  : 读取RTC时间
 * @date  : 2025-02-19
 * @author: AnRui
 * @return: uint16_t* 返回数组指针保存时间数据
 * @note  :
 */
uint16_t* RTC_read() {
    rtc_parameter_struct rps;
    rtc_current_time_get(&rps);
    time_arry [0] = READ_BCD(rps.year) + 2000;
    time_arry [1] = READ_BCD(rps.month);
    time_arry [2] = READ_BCD(rps.date);
    time_arry [3] = READ_BCD(rps.day_of_week);
    time_arry [4] = READ_BCD(rps.hour);
    time_arry [5] = READ_BCD(rps.minute);
    time_arry [6] = READ_BCD(rps.second);
    return time_arry;
}


#if RTC_ALARM 
/**
 * @desc  : RTC闹钟设置
 * @date  : 2025-02-19
 * @author: AnRui
 * @note  :
 */
void RTC_ALARM_config() {
    // 闹钟外部中断  必须配置 EXTI_17 根据手册查出来的 固定
    exti_flag_clear(EXTI_17);
    exti_init(EXTI_17, EXTI_INTERRUPT, EXTI_TRIG_RISING);
    // 重置闹钟
    rtc_alarm_disable(rtc_alarmx);
    rtc_alarm_struct ras;
    ras.alarm_mask = RTC_ALARM_MASK;
    ras.weekday_or_date = RTC_ALARM_DATE_SELECTED;
    ras.alarm_day = WRITE_BCD(RTC_ALARM_DAY);
    ras.alarm_hour = WRITE_BCD(RTC_ALARM_HOUR);
    ras.alarm_minute = WRITE_BCD(RTC_ALARM_MINUTE);
    ras.alarm_second = WRITE_BCD(RTC_ALARM_SECOND);

    ras.am_pm = (RTC_ALARM_HOUR >= 0 && RTC_ALARM_HOUR < 12) ? RTC_AM : RTC_PM; // 24小时值 上午（AM）是从午夜12点（0:00）开始，到中午11:59结束；中午12点开始就进入下午时段，一直持续到晚上11:59 。
    rtc_alarm_config(rtc_alarmx, &ras);
    // 中断配置
    nvic_irq_enable(RTC_Alarm_IRQn, 2, 2);
    rtc_interrupt_enable(rtc_int_alarmx);
    rtc_flag_clear(rtc_flag_alarmx);
    rtc_alarm_enable(rtc_alarmx);
}
/**
 * @desc  : RTC报警的回调函数
 * @date  : 2025-02-19
 * @author: AnRui
 * @note  :
 */
void RTC_Alarm_IRQHandler() {
    if (RESET != rtc_flag_get(rtc_flag_alarmx)) {
        rtc_flag_clear(rtc_flag_alarmx);
        exti_flag_clear(EXTI_17);
        rtc_alarm_hander();
    }
}
#endif 